package com.example.bootes.config;


import com.example.bootes.param.Constants;
import com.example.bootes.utils.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

/**
 * 日志拦截器
 * @author binbin.hou
 * @date 2018/12/7
 */
//@Component
//@Aspect
@Slf4j
public class LogAspect {
    /**
     * 限额限日志次的 trace id
     */
    private static final String TRACE_ID = "TRACE_ID";
    IdWorker worker = new IdWorker(1,1,1);
    /**
     * 拦截入口下所有的 public方法
     */
    @Pointcut("execution(public * com.example.bootes..*(..))")
    public void pointCut() {
    }

    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        //添加 MDC
        MDC.put(TRACE_ID, String.valueOf(worker.nextId()));
        //移除 MDC
        log.info("切面添加调用：{}",MDC.get(Constants.TRACE_ID));
    }

    @After("pointCut()")
    public void doAfter(JoinPoint joinPoint) throws Throwable {
        //移除 MDC
//        log.info("切面移除调用：{}",MDC.get(Constants.TRACE_ID));
//        MDC.remove(TRACE_ID);
    }
    @AfterReturning(value = "pointCut()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    /**
     * 拦截处理
     *
     * @param point point 信息
     * @return result
     * @throws Throwable if any
     */
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {


        Object result = point.proceed();

        return result;
    }
}
